package com.zyf.wjy.controller;

import com.zyf.wjy.entity.User;
import com.zyf.wjy.service.UserService;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;

/**
 * 登录控制器
 */
@Controller
public class LoginController {
    
    @Autowired
    private UserService userService;
    
    /**
     * 登录页面
     */
    @GetMapping("/login")
    public String loginPage() {
        return "login";
    }
    
    /**
     * 处理登录
     */
    @PostMapping("/doLogin")
    public String doLogin(@RequestParam String username, 
                         @RequestParam String password,
                         HttpSession session,
                         Model model) {
        User user = userService.login(username, password);
        if (user != null) {
            session.setAttribute("currentUser", user);
            return "redirect:/index";
        } else {
            model.addAttribute("error", "用户名或密码错误！");
            return "login";
        }
    }
    
    /**
     * 注册页面
     */
    @GetMapping("/register")
    public String registerPage() {
        return "register";
    }
    
    /**
     * 处理注册
     */
    @PostMapping("/doRegister")
    public String doRegister(User user, Model model) {
        boolean success = userService.register(user);
        if (success) {
            model.addAttribute("success", "注册成功，请登录！");
            return "login";
        } else {
            model.addAttribute("error", "用户名已存在！");
            return "register";
        }
    }
    
    /**
     * 退出登录
     */
    @GetMapping("/logout")
    public String logout(HttpSession session) {
        session.invalidate();
        return "redirect:/login";
    }
}

